<template>
  <div class="doctor-search-page">
    <TopHeader title="名医搜索" />
    <h2>名医搜索</h2>
    <div style="margin-bottom:16px;">
      <el-input v-model="searchName" placeholder="请输入医生姓名" style="width:200px;margin-right:8px;" @keyup.enter="searchDoctor" />
      <el-button type="primary" @click="searchDoctor">搜索</el-button>
      <el-button @click="resetSearch" style="margin-left:6px;">重置</el-button>
    </div>
    <div v-if="doctors.length === 0" style="color:#aaa;text-align:center;margin-top:40px;">暂无医生</div>
    <div class="doctor-list">
      <div v-for="doc in doctors" :key="doc.doc_id" class="doctor-card">
        <img :src="doc.img || defaultAvatar" class="doc-avatar" />
        <div class="doc-info">
          <div class="doc-name">{{ doc.doc_name }} <span class="doc-title">{{ doc.doc_title }}</span></div>
          <div class="doc-dept">科室：{{ deptMap[doc.depart_id2] || '未知' }}</div>
          <div class="doc-nums">电话：{{ doc.telephone }}</div>
          <div class="doc-desc">{{ getShortIntro(doc.introduction || '暂无简介') }}</div>
        </div>
        <el-button type="primary" size="small" @click="openAppointmentDialog(doc)">预约挂号</el-button>
      </div>
    </div>
    <el-dialog v-model="showDialog" title="预约挂号" width="90%">
      <div v-if="currentDoctor">
        <div style="font-weight:bold;margin-bottom:8px;">{{ currentDoctor.doc_name }} <span style="color:#888;font-size:13px;">{{ currentDoctor.doc_title }}</span></div>
        <el-form :model="form" label-width="70px" ref="formRef">
          <el-form-item label="就诊人">
            <el-input v-model="form.name" readonly />
          </el-form-item>
          <el-form-item label="电话" prop="telephone" :rules="[{ required: true, message: '请输入联系电话' }, { validator: validatePhone, trigger: 'blur' }]">
            <el-input v-model="form.telephone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="form.day" type="date" placeholder="请选择日期" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="时段">
            <el-radio-group v-model="form.timeSlot">
              <el-radio label="上午">上午</el-radio>
              <el-radio label="下午">下午</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.info" type="textarea" placeholder="可选" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="submitAppointment">确认预约</el-button>
      </template>
    </el-dialog>
    <BottomNavigation />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import TopHeader from '@/components/TopHeader.vue'
import BottomNavigation from '@/components/BottomNavigation.vue'
import { ElMessage } from 'element-plus'

const searchName = ref('')
const doctors = ref([])
const defaultAvatar = 'https://cdn-icons-png.flaticon.com/512/4140/4140048.png'

const departments = ref([]) // 科室列表
const deptMap = ref({}) // id->name 映射

const showDialog = ref(false)
const currentDoctor = ref(null)
const form = ref({
  name: '',
  telephone: '',
  day: '',
  timeSlot: '上午',
  info: ''
})
const formRef = ref(null)

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

const fetchDepartments = async () => {
  const res = await axios.get('http://localhost:8080/hospital5_war/department/findAll')
  departments.value = res.data
  deptMap.value = {}
  for (const dept of res.data) {
    deptMap.value[dept.departmentId] = dept.departmentName
  }
}

const searchDoctor = async () => {
  if (!searchName.value.trim()) {
    const res = await axios.get('http://localhost:8080/hospital5_war/doctor/findAll')
    doctors.value = (res.data || []).filter(doc => doc.recommend == 1)
    return
  }
  const res = await axios.get('http://localhost:8080/hospital5_war/doctor/findByDocName', {
    params: { doc_name: searchName.value.trim() }
  })
  doctors.value = res.data
}

const resetSearch = () => {
  searchName.value = ''
  doctors.value = []
  searchDoctor()
}

function openAppointmentDialog(doc) {
  currentDoctor.value = doc
  form.value.name = userInfo.realName || ''
  form.value.telephone = userInfo.telephone || ''
  form.value.day = ''
  form.value.timeSlot = '上午'
  form.value.info = ''
  showDialog.value = true
}
const validatePhone = (rule, value, callback) => {
  if (!/^1\d{10}$/.test(value)) {
    callback(new Error('请输入11位手机号'));
  } else {
    callback();
  }
};
const submitAppointment = async () => {
  if (!form.value.name || !form.value.telephone || !form.value.day) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (formRef.value) {
    try {
      await formRef.value.validate()
    } catch (e) {
      return
    }
  }
  await axios.post('http://localhost:8080/hospital5_war/patientDoctor/addPatientDoctor', {
    patientId: userInfo.userId || '',
    name: form.value.name,
    docId: currentDoctor.value.doc_id,
    telephone: form.value.telephone,
    day: form.value.day,
    departId2: currentDoctor.value.depart_id2,
    info: `${form.value.timeSlot} - ${form.value.info || '无备注'}`,
    status: 0
  }, {
    headers: { 'Content-Type': 'application/json' }
  })
  showDialog.value = false
  ElMessage.success('挂号成功！')
}

function getShortIntro(intro) {
  if (!intro) return '';
  return intro.length > 100 ? intro.slice(0, 100) + '...' : intro;
}

onMounted(() => {
  fetchDepartments()
  searchDoctor()
})
</script>

<style scoped>
.doctor-search-page {
  max-width: 600px;
  margin: 0 auto;
  padding: 30px 10px 80px 10px;
  background: #f5f7fa;
  min-height: 100vh;
  padding-top: 70px;
}
.doctor-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.doctor-card {
  display: flex;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(22,93,255,0.08);
  padding: 14px 12px;
  align-items: center;
}
.doc-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 14px;
  background: #e6f0ff;
}
.doc-info {
  flex: 1;
  display: block;
}
.doc-name {
  font-size: 16px;
  font-weight: bold;
  color: #165DFF;
  margin-bottom: 2px;
}
.doc-title {
  font-size: 13px;
  color: #888;
  margin-left: 6px;
}
.doc-dept {
  font-size: 13px;
  color: #888;
  margin-bottom: 2px;
}
.doc-nums {
  font-size: 13px;
  color: #faad14;
  margin-bottom: 2px;
}
.doc-desc {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}
</style> 